package service

import (
	"ginblog/model"
	errMsg "ginblog/model/err"
	"ginblog/model/request"
	"ginblog/model/response"
	"ginblog/utils"
	"gorm.io/gorm"
)

func AddUser(u *model.User) {
	//if code = u.CheckUser(); code == model.SUCCESS {
	//    if code = u.Create();code == model.
	//}
}

func GetUser(p map[string]interface{}, pageSize, pageNum int) (*response.PageInfo, errMsg.Code) {
	var (
		total    int64
		code     errMsg.Code
		pageInfo = response.PageInfo{
			Total: &total,
			List:  nil,
		}
		err error
	)
	total, err = model.CountUser(p)
	r := NewReturn()
	r.Check(err != nil && err != gorm.ErrRecordNotFound, errMsg.DB_ERROR)
	r.Check(total == 0, errMsg.SUCCESS)
	pageInfo.List, code = model.FindUsers(pageSize, pageNum)
	r.Check(code != errMsg.SUCCESS, errMsg.DB_ERROR)
	return &pageInfo, r.C
}

func Login(data *request.Login) errMsg.Code {
	var (
		u = &model.User{
			Username: data.Username,
		}
		pwd string
		err = model.Login(u)
	)
	r := NewReturn()
	r.Check(err != nil && err != gorm.ErrRecordNotFound, errMsg.DB_ERROR)
	r.Check(u.ID < 1, errMsg.ERROR_USER_NOT_EXIST)
	r.CheckDo(func() {
		pwd, _ = utils.ScryptPwd(data.Password)
	})
	r.Check(u.Password != pwd, errMsg.ERROR_PASSWORD_WRONG)
	return r.C
}

type Return struct {
	C errMsg.Code // 决定判断是否进行
	B bool        // 决定后续操作是否进行
}

func NewReturn() *Return {
	return &Return{C: errMsg.SUCCESS, B: true}
}

func (r *Return) Check(b bool, code errMsg.Code) {
	if r.C == errMsg.SUCCESS {
		if b {
			r.C = code
		}
	}
}

// 不需要返回，继续执行
func (r *Return) CheckDo(f func()) {
	if r.C == errMsg.SUCCESS && r.B {
		f()
	}
}

// 不需要返回，b决定本次操作是否进行，如果不满足本次条件，后续的操作将都不会执行
func (r *Return) IfDo(b bool, f func()) {
	if r.C == errMsg.SUCCESS && r.B {
		if b {
			f()
		} else {
			r.B = false
		}
	}
}
func (r *Return) CheckV2(b bool, code errMsg.Code, f func()) {
	if r.C == errMsg.SUCCESS {
		if b {
			if f != nil {
				f()
			} else {
				r.C = code
			}
		}
	}
}
